<?php

/**
 * 答题操作后续操作：不需要即时的操作一律放到队列
 *
 * 已废弃
 */

namespace App\Jobs;

use App\Events\UserLearnLimitCheckEvent;
use App\Models\Qh_LitQuestion;
use App\Models\Qh_Question;
use App\Models\Qh_Rank;
use App\Models\User;
use App\Service\Redis\RedisBaseService;
use Carbon\Carbon;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldBeUnique;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
use Illuminate\Support\Facades\DB;

class UserQuestionSubmitHelperJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    protected int $questionId;
    protected User $user;
    protected array $params;
    protected int $mode;    // 模式，1：刷题、2：刷题-小题、3、考试模式
    protected int $type;    // 类型，1：正常、2：错题

    /**
     * Create a new job instance.
     *
     * @return void
     */
    public function __construct($questionId, $user, $params, $mode, $type=1)
    {
        $this->questionId = $questionId;
        $this->user = $user;
        $this->params = $params;
        $this->mode = $mode;
        $this->type = $type;
    }

    /**
     * Execute the job.
     *
     * @return void
     * @throws \Throwable
     */
    public function handle(RedisBaseService $redisBaseService)
    {
        // 标准模式
        if ($this->mode == 1) {
            Db::transaction(function () use ($redisBaseService) {
                try {
                    $question = Qh_Question::findOrFail($this->questionId);

                    $log = Db::table('qh_user_question_logs')->where('userId', $this->user->id)->where('questionId', $question->id)->first();
                    if (!$log) {
                        // 记录
                        DB::table('qh_user_question_logs')->updateOrInsert([
                            'userId' => $this->user->id,
                            'qlId' => $question->qlId,
                            'courseId' => $question->courseId,
                            'knowledgeId' => $question->knowledgeId,
                            'questionId' => $question->id,
                            'result' => $this->params['result'],
                            'userAnswer' => !empty($this->params['answer']) ? $this->params['answer'] : null,
                            'created_at' => Carbon::now()
                        ]);
                    } else {
                        // 更新
                        if ($log->result != $this->params['result'] or $log->userAnswer != $this->params['answer']) {
                            Db::table('qh_user_question_logs')
                                ->where('id', $log->id)
                                ->update(['result' => $this->params['result'], 'userAnswer' => !empty($this->params['answer']) ? $this->params['answer'] : null, 'updated_at' => Carbon::now()]);
                        }
                    }

                    // 记录学习状态
                    $learn = DB::table('qh_user_learn')->where('userId', $this->user->id)->where('courseId', $question->courseId)->where('knowledgeId', $question->knowledgeId)->first();
                    if (!$learn) {
                        DB::table('qh_user_learn')->insert([
                            'userId' => $this->user->id,
                            'qlId' => $question->qlId,
                            'courseId' => $question->courseId,
                            'knowledgeId' => $question->knowledgeId,
                            'qCount' => 1,
                            'created_at' => Carbon::now()
                        ]);
                    } else {
                        DB::table('qh_user_learn')->where('userId', $this->user->id)->where('courseId', $question->courseId)->where('knowledgeId', $question->knowledgeId)->update([
                            'qCount' => $learn->qCount + 1,
                            'updated_at' => Carbon::now()
                        ]);
                    }

                    // 排名
                    $rank = Qh_Rank::where('userId', $this->user->id)->first();
                    if (!$rank) {
                        $rank = new Qh_Rank();
                        $rank->userId = $this->user->id;
                    }

                    // 正确
                    if ($this->params['result'] == 1) {
                        // 更新正确次数
                        $question->rightCount += 1;
                        $rank->rightCount += 1;

                        // 错题出库
                        // \Log::debug('错题出库:'. $question->id);
                        if ($this->type == 2) {
                            $redisBaseService->popWrongOrCollectQuestion($this->user->id, $question, 1);
                        }
                    }

                    // 错误
                    if ($this->params['result'] == 2) {
                        // 更新错误次数
                        $question->wrongCount += 1;
                        $rank->wrongCount += 1;

                        // 错题入库
                        if ($this->type != 2) {
                            $redisBaseService->pushWrongOrCollectQuestionToDb($this->user->id, $question, 1);
                        }
                    }

                    $rank->save();
                    $question->save();
                }catch (\Exception $e) {
                    \Log::error($e->getMessage());
                    \Log::error('[答题助手]处理异常', [
                        'userId' => $this->user->id,
                        'questionId' => $this->questionId,
                        'params' => $this->params
                    ]);
                }
            }, 5);
        }
        // 小题模式
        elseif ($this->mode == 2) {
            if (!empty($this->params['answer'])) {
                if (is_array($this->params['answer'])) {
                    $userAnswer = implode(',', $this->params['answer']);
                } else {
                    $userAnswer = $this->params['answer'];
                }
            } else {
                $userAnswer = null;
            }

            $question = Qh_LitQuestion::findOrFail($this->questionId);
            if (empty($question->knowledgeId)) {
                $parentQuestion = Qh_Question::find($question->parentId);
                if ($parentQuestion) {
                    $question->qlId = $parentQuestion->qlId;
                    $question->courseId = $parentQuestion->courseId;
                    $question->knowledgeId = $parentQuestion->knowledgeId;
                    $question->save();
                }
            }

            Db::transaction(function () use ($question, $userAnswer) {
                try {
                    $questionIdInLogs = intval('999999' . $question->id);
                    $log = Db::table('qh_user_question_logs')->where('userId', $this->user->id)->where('questionId', $questionIdInLogs)->first();
                    if (!$log) {
                        // 记录
                        DB::table('qh_user_question_logs')->updateOrInsert([
                            'userId' => $this->user->id,
                            'qlId' => $question->qlId,
                            'courseId' => $question->courseId,
                            'knowledgeId' => $question->knowledgeId,
                            'questionId' => $questionIdInLogs,
                            'result' => $this->params['result'],
                            'userAnswer' => $userAnswer,
                            'created_at' => Carbon::now()
                        ]);
                    } else {
                        // 更新
                        if ($log->result != $this->params['result'] or $log->userAnswer != $userAnswer) {
                            Db::table('qh_user_question_logs')
                                ->where('id', $log->id)
                                ->update(['result' => $this->params['result'], 'userAnswer' => $userAnswer, 'updated_at' => Carbon::now()]);
                        }
                    }

                    // 正确
                    if ($this->params['result'] == 1) {
                        // 更新正确次数
                        $question->rightCount += 1;
                    }

                    // 错误
                    if ($this->params['result'] == 2) {
                        // 更新错误次数
                        $question->wrongCount += 1;
                    }

                    $question->save();
                }catch (\Exception $e) {
                    \Log::error($e->getMessage());
                    \Log::error('[小题答题助手]处理异常', [
                        'userId' => $this->user->id,
                        'questionId' => $this->questionId,
                        'params' => $this->params
                    ]);
                }
            });
        }
        // 考试模式
        elseif ($this->mode == 3) {
            Db::transaction(function () {
                try {
                    $question = Qh_Question::findOrFail($this->questionId);
                    $log = Db::table('qh_user_kaoshi_question_logs')->where('userId', $this->user->id)->where('questionId', $question->id)->first();
                    if (!$log) {
                        // 记录
                        DB::table('qh_user_kaoshi_question_logs')->insert([
                            'userId' => $this->user->id,
                            'qlId' => $question->qlId,
                            'courseId' => $question->courseId,
                            'knowledgeId' => $question->knowledgeId,
                            'questionId' => $question->id,
                            'result' => $this->params['result'],
                            'userAnswer' => !empty($this->params['answer']) ? $this->params['answer'] : null,
                            'created_at' => Carbon::now()
                        ]);
                    } else {
                        // 更新
                        if ($log->result != $this->params['result'] or $log->userAnswer != $this->params['answer']) {
                            Db::table('qh_user_kaoshi_question_logs')
                                ->where('id', $log->id)
                                ->update(['result' => $this->params['result'], 'userAnswer' => !empty($this->params['answer']) ? $this->params['answer'] : null, 'updated_at' => Carbon::now()]);
                        }
                    }
                }catch (\Exception $e) {
                    \Log::error($e->getMessage());
                    \Log::error('[考试答题助手]处理异常', [
                        'userId' => $this->user->id,
                        'questionId' => $this->questionId,
                        'params' => $this->params
                    ]);
                }
            });
        }

        \Log::debug('[答题助手]处理完成', [
            'mode' => $this->mode,
            'userId' => $this->user->id,
            'questionId' => $this->questionId,
        ]);
    }
}
